package tools;


public class LogonPacket extends Packet {
	public String userName;//可以将要发送的信息进行封装成一个类  在对这个类进行序列化和反序列化
	public String password;

	public byte[] serialize() {
		int totalLength = 12 + userName.getBytes().length + password.getBytes().length;

		byte[] buffer = new byte[totalLength];

		int offset = 0;

		// copy totalLength to buffer
		byte[] totalLengthBuffer = Util.int2bytes(totalLength);
		System.arraycopy(totalLengthBuffer, 0, buffer, offset, 4);
		offset += 4;

		// copy packet type to buffer
		byte[] packetTypeBuffer = Util.int2bytes(Service.PACKET_TYPE.C2S_LOGON);
		System.arraycopy(packetTypeBuffer, 0, buffer, offset, 4);
		offset += 4;

		// copy user name length to buffer
		byte[] userNameLengthBuffer = Util.int2bytes(userName.getBytes().length);
		System.arraycopy(userNameLengthBuffer, 0, buffer, offset, 4);
		offset += 4;

		// copy user name to buffer
		System.arraycopy(userName.getBytes(), 0, buffer, offset, userName.getBytes().length);
		offset += userName.getBytes().length;

		// copy password to buffer
		System.arraycopy(password.getBytes(), 0, buffer, offset, password.getBytes().length);
		offset += password.getBytes().length;

		return buffer;
	}

	public void unserialize(byte[] data) {
		System.out.println(data.length);
		// decode total length
		int totalLength = Util.bytes2int(data, 0);

		// decode user name length
		int userNameLength = Util.bytes2int(data, 8);

		userName = new String(data, 12, userNameLength);

		password = new String(data, 12 + userNameLength, totalLength - 12 - userNameLength);
	}
}
